package http

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"net/url"
	"time"
)

func Get(url string) (string, error) {
	//get请求
	//http.Get的参数必须是带http://协议头的完整url,不然请求结果为空
	timeout := time.Duration(5 * time.Second)
	client := http.Client{
		Timeout: timeout,
	}
	resp, err := client.Get(url)
	defer resp.Body.Close()
	if err != nil {
		return "", err
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	return string(body), nil
}

func PostWithJson(url string, data interface{}) string {
	//post请求提交json数据
	ba, _ := json.Marshal(data)
	resp, err := http.Post(url, "application/json", bytes.NewBuffer([]byte(ba)))
	defer resp.Body.Close()
	if err != nil {
		return ""
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return ""
	}

	return string(body)
}

func PostWithUrlencoded(urlpath string, data map[string]string) string {
	//post请求提交application/x-www-form-urlencoded数据
	form := make(url.Values)
	for k, v := range data {
		form.Add(k, v)
	}
	resp, _ := http.PostForm(urlpath, form)
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	return string(body)
}
